Week 9: Transformations and MANOVA
PLS 206 — self-study (no class Wednesday, November 25)
There is no lecture for this unit: its Wednesday falls in Thanksgiving week. Work through this page on your own, one step at a time. Each step has the code, its output, and a picture.
Two ideas, one page:
- Transformations. When a response is skewed and its spread grows with its mean, put it on a scale where a straight line fits. Then bring the answer back to the original units.
- MANOVA. When you measure several responses on the same samples, ask one question about all of them at once instead of running one ANOVA per response. PERMANOVA does the same job when the responses are species counts full of zeros.
To run it yourself, download either version and open it in RStudio. It reads the data straight from the course website, so there is no file to download and no working directory to set:
- Week9_MANOVA_selfstudy.R: the plain script. Each block is tagged
[CORE],[HANDY], or[DEMO]in a comment. - Week9_MANOVA_selfstudy.qmd: this page as a Quarto notebook.
Every block of code on this page carries one of three labels:
- Core The analysis. Code you would run on your own data: fit the model, read the output, check the diagnostics, report it. Start here for the problem sets.
- Handy Useful, not essential. Wrangling, plotting, and small helpers that make the core easier. Worth knowing; skip on a first read.
- Demo For the lecture only. Simulated data, sums done by hand, and the code behind slide figures. It shows why the core works. Folded: click to open.
# install.packages(c("ggplot2", "patchwork", "MASS", "vegan"))
library(ggplot2)
library(patchwork)
library(MASS) # boxcox() and lda()
library(vegan) # adonis2() and betadisper(), plus the dune dataPart A. Transformations
1) The data: 60 soil cores
Each core has its soil organic carbon (SOC, %) and its microbial biomass carbon (µg C per g of soil). The question: how does microbial biomass change with soil carbon? (Hypothetical, simulated data.)
soil <- read.csv("https://greymonroe.github.io/PLS_206/data/soil_microbes.csv")
head(soil) core soc microbial_biomass
1 1 0.56 52.6
2 2 1.51 184.8
3 3 3.56 313.0
4 4 3.30 187.4
5 5 1.59 76.1
6 6 2.15 245.0
p_soil <- ggplot(soil, aes(soc, microbial_biomass)) +
geom_point(size = 2) +
labs(x = "Soil organic carbon (%)", y = "Microbial biomass (µg C / g)") +
theme_classic(base_size = 14)
p_soil
Two things stand out. The cloud curves upward, and it fans out: cores with more carbon vary far more than cores with little.
2) A straight line on the raw scale
m_raw <- lm(microbial_biomass ~ soc, data = soil)
grid <- data.frame(soc = seq(min(soil$soc), max(soil$soc), length.out = 100))
fit_raw <- cbind(grid, predict(m_raw, grid, interval = "confidence"))
p_soil +
geom_ribbon(data = fit_raw, aes(soc, ymin = lwr, ymax = upr), inherit.aes = FALSE, fill = "red", alpha = 0.2) +
geom_line(data = fit_raw, aes(soc, fit), colour = "red", linewidth = 1)
The line misses the curve: it runs above the data in the middle and below it at both ends. The residuals show the second problem, the fan:
plot(m_raw, which = 1)
Residuals that spread out as the fitted values grow break the equal-variance assumption, so the standard errors and p-values of this model can’t be trusted.
3) Log the response
A log turns multiplying into adding. If biomass grows by the same percentage for each extra unit of carbon, then log(biomass) grows by the same amount, which is a straight line.
Demo: the response before and after the log
h_raw <- ggplot(soil, aes(microbial_biomass)) + geom_histogram(bins = 15, fill = "grey70", colour = "black") +
labs(x = "Microbial biomass (µg C / g)", y = "Cores", title = "Raw: long right tail") + theme_classic(base_size = 14)
h_log <- ggplot(soil, aes(log(microbial_biomass))) + geom_histogram(bins = 15, fill = "lightblue", colour = "black") +
labs(x = "log(microbial biomass)", y = "Cores", title = "Log: symmetric") + theme_classic(base_size = 14)
h_raw + h_log
4) Fit the line on the log scale
Put the log inside the formula. R fits the model to log(biomass); the data frame stays as it is.
m_log <- lm(log(microbial_biomass) ~ soc, data = soil)
summary(m_log)
Call:
lm(formula = log(microbial_biomass) ~ soc, data = soil)
Residuals:
Min 1Q Median 3Q Max
-1.2192 -0.3108 -0.0080 0.3151 0.9772
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 3.93354 0.15281 25.742 < 2e-16 ***
soc 0.51149 0.05858 8.731 3.69e-12 ***
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Residual standard error: 0.4619 on 58 degrees of freedom
Multiple R-squared: 0.5679, Adjusted R-squared: 0.5605
F-statistic: 76.24 on 1 and 58 DF, p-value: 3.69e-12
fit_log <- cbind(grid, predict(m_log, grid, interval = "confidence"))
ggplot(soil, aes(soc, log(microbial_biomass))) +
geom_point(size = 2) +
geom_ribbon(data = fit_log, aes(soc, ymin = lwr, ymax = upr), inherit.aes = FALSE, fill = "blue", alpha = 0.2) +
geom_line(data = fit_log, aes(soc, fit), colour = "blue", linewidth = 1) +
labs(x = "Soil organic carbon (%)", y = "log(microbial biomass)") +
theme_classic(base_size = 14)
On the log scale the points follow the line and the spread is even. The residual plot agrees: no fan.
plot(m_log, which = 1)
5) Back-transform to the original units
Nobody thinks in log(µg C / g). Undo the log with exp(): on the fitted line, on its confidence band, and on the slope.
fit_back <- fit_log
fit_back[, c("fit", "lwr", "upr")] <- exp(fit_log[, c("fit", "lwr", "upr")])
p_soil +
geom_ribbon(data = fit_back, aes(soc, ymin = lwr, ymax = upr), inherit.aes = FALSE, fill = "blue", alpha = 0.2) +
geom_line(data = fit_back, aes(soc, fit), colour = "blue", linewidth = 1)
The model is a straight line on the log scale and a curve in the original units, and it follows the data. Back-transformed, the slope becomes a multiplier:
exp(coef(m_log))(Intercept) soc
51.087681 1.667772
exp(confint(m_log)) 2.5 % 97.5 %
(Intercept) 37.624918 69.367625
soc 1.483237 1.875266
Each extra 1% of soil carbon multiplies microbial biomass by about 1.67 (95% CI 1.48 to 1.88), a 67% increase. Two things to remember when you report a back-transformed model:
- The back-transformed line is the geometric mean (roughly the median) of biomass at each SOC, not the arithmetic mean. With a long right tail, the arithmetic mean sits above it.
- Back-transform the ends of the confidence interval, never the standard error. That is why the band is wider above the line than below it.
6) Let Box-Cox pick the power
Not sure which transformation? boxcox() tries a family of powers, y^λ, and shows how well each one fits. λ = 1 is no transformation, λ = 0.5 is the square root, λ = 0 is the log, λ = −1 is the reciprocal.
bc <- boxcox(m_raw, lambda = seq(-1, 1, 0.05))
bc$x[which.max(bc$y)] # the best lambda[1] 0.01010101
The best λ is 0. The 95% interval (the dashed lines, about −0.25 to 0.27) includes 0 and excludes the square root (0.5) and no transformation (1): the log is the right call. In practice, treat Box-Cox as a guide and round to a transformation you can explain (log, square root, reciprocal). Box-Cox needs a positive response.
7) Which transformation for which data
| Your response | Transformation | The alternative from Week 3 |
|---|---|---|
| Positive, right-skewed, spread grows with the mean (biomass, concentrations, gene expression) | log(y) |
Gamma or lognormal GLM, family = Gamma(link = "log") |
| Counts (insects, lesions, seeds) | sqrt(y) |
Poisson or negative binomial GLM |
| Proportions between 0 and 1 (germination, cover) | logit, qlogis(p) |
Binomial GLM |
| Contains zeros and needs a log | log(y + 1), with care: the answer depends on the “+1” |
A GLM handles zeros directly |
| Hopeless distribution, only the order matters | rank(y) |
Non-parametric tests (Kruskal-Wallis, Week 1) |
A transformation and a GLM answer slightly different questions. lm(log(y) ~ x) models the mean of log(y), the geometric mean. glm(y ~ x, family = Gamma(link = "log")) models the log of the mean of y, the arithmetic mean. For skewed positive data both are standard; use the GLM when you need predictions of the average in original units, or when the data have zeros.
Handy: the logit and its inverse
p <- c(0.05, 0.5, 0.95)
qlogis(p) # logit: log(p / (1 - p))[1] -2.944439 0.000000 2.944439
Handy: the logit and its inverse
plogis(qlogis(p)) # inverse logit brings it back[1] 0.05 0.50 0.95
8) Transforming predictors: scale()
Predictors can be transformed too. scale() centres a variable (subtracts its mean) and divides by its standard deviation, so every predictor is in standard-deviation units. You used it for PCA and clustering. In a regression it changes the units of a slope, not the fit.
soil$soc_z <- as.numeric(scale(soil$soc))
coef(lm(log(microbial_biomass) ~ soc_z, data = soil)) # change in log(biomass) per 1 SD of SOC(Intercept) soc_z
5.1619689 0.5250677
Same model, same p-value, same predictions; only the slope’s units changed. Scaling is useful when you compare slopes of predictors measured in different units, or before ridge and lasso (Week 6).
Part B. MANOVA: several responses at once
9) The data: three wines, three chemicals
The wine data from Week 1: 178 wines from three cultivars, each with 13 chemical measurements. Take three of them, alcohol (%), flavanoids, and colour intensity, and ask: do the cultivars differ in their chemistry?
wine <- read.csv("https://greymonroe.github.io/PLS_206/data/winedata.csv")
table(wine$Cultivar)
barbera barolo gringnolino
48 59 71
Handy: the three responses in long format, for plotting
wine_long <- data.frame(Cultivar = rep(wine$Cultivar, 3),
response = rep(c("Alcohol", "Flav", "Color"), each = nrow(wine)),
value = c(wine$Alcohol, wine$Flav, wine$Color))
wine_long$response <- factor(wine_long$response, levels = c("Alcohol", "Flav", "Color"))p_wine <- ggplot(wine_long, aes(Cultivar, value)) +
geom_jitter(width = 0.15, alpha = 0.4) +
facet_wrap(~response, scales = "free_y") +
labs(x = NULL, y = NULL) +
theme_classic(base_size = 14)
p_wine
10) Why not just run three ANOVAs?
Two reasons.
- More tests, more false positives. Three ANOVAs at α = 0.05 give roughly a 14% chance that at least one is “significant” by luck. Thirteen chemicals give about 49%.
- ANOVAs look at one response at a time, and miss differences that only show up together. This one is the bigger deal. Here is a demonstration on two wildflower populations, measuring petal length and petal width (mm). The two measurements are strongly correlated: long petals are wide petals. Population B’s petals are a little longer and a little narrower for their length. (Hypothetical, simulated data.)
Demo: simulate two populations that differ in petal shape
set.seed(1)
petal_pop <- function(n, mean_length, mean_width) {
z <- mvrnorm(n, c(mean_length, mean_width), matrix(c(4, 3.6, 3.6, 4), 2)) # correlation 0.9
data.frame(length = z[, 1], width = z[, 2])
}
a <- petal_pop(25, 20, 10); a$population <- "A"
b <- petal_pop(25, 20.6, 9.4); b$population <- "B"
petals <- rbind(a, b)One ANOVA per response finds nothing:
anova(lm(length ~ population, data = petals))Analysis of Variance Table
Response: length
Df Sum Sq Mean Sq F value Pr(>F)
population 1 4.163 4.1631 1.0077 0.3205
Residuals 48 198.292 4.1311
anova(lm(width ~ population, data = petals))Analysis of Variance Table
Response: width
Df Sum Sq Mean Sq F value Pr(>F)
population 1 4.348 4.3482 1.0406 0.3128
Residuals 48 200.568 4.1785
Both p-values are about 0.3. Now one MANOVA on both responses together:
summary(manova(cbind(length, width) ~ population, data = petals)) Df Pillai approx F num Df den Df Pr(>F)
population 1 0.42719 17.526 2 47 2.057e-06 ***
Residuals 48
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
p = 2 × 10⁻⁶. The picture shows why:
Demo: the two populations, each response alone and both together
pal <- c(A = "#0070C0", B = "#ED7D31")
side_l <- ggplot(petals, aes(population, length, colour = population)) + geom_jitter(width = 0.15) +
scale_colour_manual(values = pal, guide = "none") + labs(x = NULL, y = "Petal length (mm)", title = "Length alone") +
theme_classic(base_size = 14)
side_w <- ggplot(petals, aes(population, width, colour = population)) + geom_jitter(width = 0.15) +
scale_colour_manual(values = pal, guide = "none") + labs(x = NULL, y = "Petal width (mm)", title = "Width alone") +
theme_classic(base_size = 14)
both <- ggplot(petals, aes(length, width, colour = population)) + geom_point(size = 2) +
scale_colour_manual(values = pal) + labs(x = "Petal length (mm)", y = "Petal width (mm)", title = "Both together") +
theme_classic(base_size = 14)
(side_l | side_w | both) + plot_layout(widths = c(1, 1, 2))
Each response on its own is a big overlapping smear. Together, the two populations sit on two parallel bands: for any petal length, B’s petals are narrower. MANOVA uses the correlation between the responses, so it sees the shape difference that each single ANOVA misses.
11) Fit a MANOVA
manova() works like lm(), with the responses bound together by cbind() on the left of the ~.
m_wine <- manova(cbind(Alcohol, Flav, Color) ~ Cultivar, data = wine)
summary(m_wine, test = "Pillai") Df Pillai approx F num Df den Df Pr(>F)
Cultivar 2 1.4718 161.62 6 348 < 2.2e-16 ***
Residuals 175
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
How to read it:
- Pillai’s trace (1.47 here) is the test statistic: how much of the variation in the three responses, taken together, lines up with cultivar. It runs from 0 (no difference) up to the smaller of the number of responses and the number of groups minus 1 (2 here). Pillai is the default and the most robust of the four statistics R offers (
"Wilks","Hotelling-Lawley","Roy"); stick with it. - approx F, Pr(>F): the p-value, < 2 × 10⁻¹⁶. The three cultivars differ in their chemistry.
12) Follow up: which responses differ?
A significant MANOVA says the groups differ somewhere. summary.aov() gives one ANOVA per response, from the same model:
summary.aov(m_wine) Response Alcohol :
Df Sum Sq Mean Sq F value Pr(>F)
Cultivar 2 70.795 35.397 135.08 < 2.2e-16 ***
Residuals 175 45.859 0.262
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Response Flav :
Df Sum Sq Mean Sq F value Pr(>F)
Cultivar 2 128.522 64.261 233.93 < 2.2e-16 ***
Residuals 175 48.074 0.275
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Response Color :
Df Sum Sq Mean Sq F value Pr(>F)
Cultivar 2 551.42 275.708 120.66 < 2.2e-16 ***
Residuals 175 399.86 2.285
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
All three differ strongly (every p < 2 × 10⁻¹⁶). Plot each response with its cultivar means and 95% confidence intervals over the raw data:
Handy: cultivar means and 95% CIs for each response
means_ci <- function(response) {
m <- lm(reformulate("Cultivar", response), data = wine)
nd <- data.frame(Cultivar = sort(unique(wine$Cultivar)))
data.frame(nd, response = response, predict(m, nd, interval = "confidence"))
}
wine_means <- do.call(rbind, lapply(c("Alcohol", "Flav", "Color"), means_ci))
wine_means$response <- factor(wine_means$response, levels = levels(wine_long$response))p_wine +
geom_pointrange(data = wine_means, aes(Cultivar, fit, ymin = lwr, ymax = upr), colour = "red", size = 0.6)
Barolo is highest in alcohol and flavanoids; barbera is lowest in flavanoids and deepest in colour; grignolino (spelled gringnolino in the data) is the lightest and lowest in alcohol. For pairwise comparisons within one response, use TukeyHSD(aov(Flav ~ Cultivar, data = wine)) as in Week 1.
13) The discriminant view: which combination separates the groups?
MANOVA tests whether the groups differ. Linear discriminant analysis (LDA) shows how: it finds the weighted combinations of the responses that pull the groups furthest apart. It is the PCA of between-group differences.
lda_wine <- lda(Cultivar ~ Alcohol + Flav + Color, data = wine)
lda_wine$scaling # weights of each response on LD1 and LD2 LD1 LD2
Alcohol 0.3753637 -1.5687638
Flav 1.8823875 -0.2668881
Color -0.5175554 -0.2211328
lda_wine$svd^2 / sum(lda_wine$svd^2) # share of the separation on each axis[1] 0.7249312 0.2750688
scores <- data.frame(predict(lda_wine)$x, Cultivar = wine$Cultivar)
ggplot(scores, aes(LD1, LD2, colour = Cultivar)) +
geom_point(size = 2, alpha = 0.7) +
stat_ellipse(linewidth = 1) +
theme_classic(base_size = 14)
The three cultivars form three nearly separate clouds. LD1 carries 72% of the separation, and its largest weight is on flavanoids: LD1 is mostly the flavanoid axis, splitting low-flavanoid barbera from the other two. LD2 (28%) is mostly alcohol, splitting high-alcohol barolo from grignolino.
14) Assumptions
MANOVA is the multivariate version of ANOVA, so it inherits ANOVA’s assumptions, each in a multivariate form:
- Independent samples. Same as always.
- Residuals roughly normal, for each response. Check each response’s residuals (as in Week 2), and transform a skewed response first (Part A).
- Similar spread across groups, now for every response and for the correlations between them (equal covariance matrices). A quick look: the standard deviation of each response in each group.
aggregate(cbind(Alcohol, Flav, Color) ~ Cultivar, data = wine, FUN = sd) Cultivar Alcohol Flav Color
1 barbera 0.5302413 0.2935041 2.3109421
2 barolo 0.4621254 0.3974936 1.2385728
3 gringnolino 0.5379642 0.7057008 0.9249293
The spreads differ by up to a factor of about 2.5 (colour in barbera vs grignolino), which Pillai’s trace tolerates, especially with groups of similar size. When the responses are far from normal (counts with many zeros, presence/absence), or there are more responses than samples, MANOVA is the wrong tool. That is where PERMANOVA comes in.
Part C. PERMANOVA: when the responses are species
15) The data: plants in 20 Dutch meadows
The dune data in vegan: cover scores of 30 plant species in 20 meadows, plus each meadow’s management (BF biological farming, HF hobby farming, NM nature conservation, SF standard farming). Thirty responses, twenty samples, and mostly zeros: no MANOVA will cope.
data(dune, dune.env)
dim(dune)[1] 20 30
mean(dune == 0) # share of zeros[1] 0.6716667
table(dune.env$Management)
BF HF NM SF
3 5 6 6
PERMANOVA works on distances between samples instead of the raw responses. For species data the usual distance is Bray-Curtis: 0 when two meadows hold the same species at the same cover, 1 when they share none. It then asks whether meadows under the same management are closer to each other than to meadows under other management, and gets its p-value by shuffling the management labels many times.
16) Look first: an ordination of the meadows
An NMDS (non-metric multidimensional scaling) draws the meadows in 2-D so that close points have similar species.
set.seed(1)
nmds <- metaMDS(dune, distance = "bray", k = 2, trace = FALSE)
nmds$stress # below 0.2 is a fair 2-D picture[1] 0.1183186
pts <- data.frame(scores(nmds, display = "sites"), Management = dune.env$Management)
centres <- aggregate(cbind(NMDS1, NMDS2) ~ Management, data = pts, FUN = mean)
ggplot(pts, aes(NMDS1, NMDS2, colour = Management)) +
geom_point(size = 3) +
geom_point(data = centres, shape = 4, size = 6, stroke = 2) +
labs(caption = "X = group centroid") +
theme_classic(base_size = 14)
The nature-conservation meadows (NM) sit apart from the farmed ones. PERMANOVA tests whether those centroids differ by more than chance.
17) Check the assumption first: similar spread
PERMANOVA assumes the groups are about equally spread out. If one group is much more scattered than another, PERMANOVA can call it a difference in centroids when it is really a difference in spread. betadisper() measures each meadow’s distance to its group centroid, and permutest() tests whether the groups differ in that.
dune_bc <- vegdist(dune, method = "bray")
disp <- betadisper(dune_bc, dune.env$Management)
set.seed(1)
permutest(disp, permutations = 999)
Permutation test for homogeneity of multivariate dispersions
Permutation: free
Number of permutations: 999
Response: Distances
Df Sum Sq Mean Sq F N.Perm Pr(>F)
Groups 3 0.13831 0.046104 1.9506 999 0.154
Residuals 16 0.37816 0.023635
p = 0.15: no evidence that the spreads differ. The assumption holds, so a PERMANOVA result will be about the centroids.
18) Run the PERMANOVA
adonis2() takes a formula like lm(), with the whole species table on the left.
set.seed(1)
adonis2(dune ~ Management, data = dune.env, method = "bray", permutations = 999)Permutation test for adonis under reduced model
Permutation: free
Number of permutations: 999
adonis2(formula = dune ~ Management, data = dune.env, permutations = 999, method = "bray")
Df SumOfSqs R2 F Pr(>F)
Model 3 1.4686 0.34161 2.7672 0.002 **
Residual 16 2.8304 0.65839
Total 19 4.2990 1.00000
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Management explains 34% of the variation in species composition (R² = 0.34), p = 0.002: meadows under different management hold different plant communities. With 999 shuffles the smallest possible p-value is 0.001, so set set.seed() and report the number of permutations.
Several predictors work like a multiple regression. Use by = "margin" so each term is tested after the others (the design here is unbalanced):
set.seed(1)
adonis2(dune ~ Use + Management, data = dune.env, method = "bray", permutations = 999, by = "margin")Permutation test for adonis under reduced model
Marginal effects of terms
Permutation: free
Number of permutations: 999
adonis2(formula = dune ~ Use + Management, data = dune.env, permutations = 999, method = "bray", by = "margin")
Df SumOfSqs R2 F Pr(>F)
Use 2 0.3757 0.08740 1.0715 0.383
Management 3 1.2912 0.30034 2.4547 0.006 **
Residual 14 2.4547 0.57099
Total 19 4.2990 1.00000
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Management still matters (p = 0.006) once land use is accounted for, while land use adds nothing beyond management (p = 0.38).
19) Which test, when
| Responses | Test | R |
|---|---|---|
| One, roughly normal | ANOVA / linear model | lm(y ~ group) |
| Several, roughly normal, more samples than responses | MANOVA | manova(cbind(y1, y2, y3) ~ group) |
| Many, non-normal, zeros (species, OTUs, gene counts) | PERMANOVA | adonis2(community ~ group, method = "bray") |
Grey’s 2025 slides for this unit are on the module page for reference.